package com.mgl.net;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public void startServer(View view) {
        new Thread() {
            @Override
            public void run() {

                try {
                    ServerSocket server = new ServerSocket(5555);

                    while (true) {
                        Socket sk = server.accept();

//                        InputStream in = sk.getInputStream();

//		            BufferedInputStream oin = new BufferedInputStream(in, 256);
                        BufferedReader reader = new BufferedReader(new InputStreamReader(sk.getInputStream()));
                        String line = reader.readLine();

                        Log.i("M", line);

                        System.out.println(reader.readLine() + "I'm back");
                        OutputStream out = sk.getOutputStream();
                        out.write("lalala".getBytes());
                        reader.close();
                        out.close();
                        sk.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } .start();
    }


    public void sendToServer(View view) {
        new Thread() {
            @Override
            public void run() {

                try {
                    Socket sk = new Socket("192.168.253.3", 5555);


                    BufferedReader reader = new BufferedReader(new InputStreamReader(sk.getInputStream()));
                    OutputStream out = sk.getOutputStream();
                    out.write("I am From my Phone\n".getBytes());
                    String line = reader.readLine();
                    Log.i("M", "Line....." + line);
                    out.close();
                    sk.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } .start();
    }
}
